import os
import os.path
import sys
from operator import itemgetter

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

import click

from dp_analysis.analysis.base import DrawBase
from dp_analysis.db.connection import Mysql
from dp_analysis.utils.decorate import decorate


class DrawUser(DrawBase):
    """
    绘制每个等级用户的VIP和非VIP数量
    """

    def __init__(self):
        super().__init__()
        self.base_sql = "SELECT user_level, COUNT(*) FROM shop_comment WHERE is_vip={} "

        self.save_path = "user/"

    @decorate(obj_name="DrawUser")
    def analyse(self, db, region):
        if region == "all":
            sql = "SELECT user_level, COUNT(*) FROM shop_comment WHERE is_vip=%d GROUP BY user_level;"
        else:
            sql = "SELECT a.user_level, COUNT(a.user_level) FROM shop_comment a, shop_info b " \
                  "WHERE a.shop_id=b.shop_id AND a.is_vip=%d AND b.region={region!r} " \
                  "GROUP BY a.user_level;".format(region=region)
        with Mysql("dp", db) as mysql:
            connection = mysql.engine.connect()

            # 获取所有的用户等级
            distinct_sql = "SELECT DISTINCT user_level FROM shop_comment;"
            user_level_list = [user_level for (user_level, ) in mysql.engine.execute(distinct_sql).fetchall()]
            user_level_list.sort()

            # 读取非 VIP 用户数量
            not_vip_dict = dict()
            for (user_level, user_count) in connection.execute(sql % 0).fetchall():
                not_vip_dict.setdefault(user_level, user_count)
            for user_level in user_level_list:
                not_vip_dict.setdefault(user_level, 0)
            not_vip_list = [not_vip for (_, not_vip) in sorted(not_vip_dict.items(), key=itemgetter(0))]

            # 读取 VIP 用户数量
            vip_dict = dict()
            for (user_level, user_count) in connection.execute(sql % 1).fetchall():
                vip_dict.setdefault(user_level, user_count)
            for user_level in user_level_list:
                vip_dict.setdefault(user_level, 0)
            vip_list = [vip for (_, vip) in sorted(vip_dict.items(), key=itemgetter(0))]

        region = region if region != "all" else None
        self.draw_user_bar(user_level_list, vip_list, not_vip_list, self.save_path, region=region)


@click.command()
@click.option("--db", default=0, help="请选择使用的数据库")
@click.option("--region", default="all", help="12大地区通过helpers.py获取\n只能指定单个地区")
def main(db, region):
    draw = DrawUser()
    draw.analyse(db, region)


if __name__ == '__main__':
    main()
